
import { QueryParams } from "@/types";
import { computed, onMounted, Ref, ref } from "vue";

interface Options {
    format: (item: any) => any
}

export default function (queryData: (params: QueryParams) => Promise<any>, options?: Options) {

    const data: Ref<any[]> = ref([]);
    const current = ref(1);
    const pageSize = ref(10);
    const total = ref(30);
    const loading = ref(false);

    const { format = undefined } = options != undefined ? options : {}

    //{ pageSize, page, sortField, sortOrder }
    const request = async (params: QueryParams) => {
        loading.value = true;
        const response = await queryData(params);
        if (response != undefined && response.status == 200) {
            data.value = format == undefined ? response.data.items : response.data.items.map(format);
            current.value = params.page;
            pageSize.value = params.pageSize;
            total.value = response.data.total;
        }
        loading.value = false;
    };


    onMounted(() => {
        request({
            pageSize: pageSize.value,
            page: current.value
        });
    });

    const pagination = computed(() => ({
      total: total.value,
      current: current.value,
      pageSize: pageSize.value,
    }));

    return {
        data,
        current,
        pageSize,
        total,
        loading,
        request,
        pagination
    };
}
